#include <stdio.h>
#include <stdlib.h>
#include <mqueue.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include "msg_queue.h"

mqd_t create_msg_queue() {
    struct mq_attr attr;
    attr.mq_flags = 0; //消息队列的标志：0或O_NONBLOCK,用来表示是否阻塞
    attr.mq_maxmsg = 10; //消息队列的最大消息数
    attr.mq_msgsize = MAX_MSG_SIZE; //消息队列中每个消息的最大字节数
    attr.mq_curmsgs = 0; //消息队列中当前的消息数目

    mqd_t mq = mq_open(QUEUE_NAME, O_CREAT | O_WRONLY, 0666, &attr);
    if (mq == (mqd_t)-1) {
        perror("mq_open failed");
        exit(EXIT_FAILURE);
    }
    return mq;
}

void send_to_queue(mqd_t mq, const char* msg) {
    if (mq_send(mq, msg, strlen(msg) + 1, 0) == -1) {
        perror("mq_send failed");
    }
}

void receive_from_queue(mqd_t mq, char* buffer) {
    ssize_t bytes = mq_receive(mq, buffer, MAX_MSG_SIZE, NULL);
    if (bytes == -1) {
        perror("mq_receive failed");
    }
}

void close_msg_queue(mqd_t mq) {
    mq_close(mq);
    mq_unlink(QUEUE_NAME);
}